﻿using Microsoft.AspNetCore.Mvc;
using MRMDS.Module;
using MRMDS.Module.Response;
using MRMDS.Utils;

namespace Demo.Controllers
{
    [ApiController]
    public class ManagerRelateController : ControllerBase
    {
        private readonly GlobalManager global;
        private readonly ILogger<ActorRelateController> _logger;
        public ManagerRelateController(ILogger<ActorRelateController> logger)
        {
            _logger = logger;
            global = GlobalManager.Instance;
        }

        [Route("Hello")]
        [HttpGet]
        public string TestPrint()
        {
            Logger.Write("User Connect Test");
            return "Hello there is MRMDS!";
        }


        [Route("Login")]
        [HttpPost]
        public string? Login([FromQuery] string token, [FromQuery] string type)
        {
            if (!Root.IsTokenValide(token))
            {
                Logger.Write($"User Login Fail(0:token invalid).(token:{token},type:{type})");
                return null;
            }
            if (global.Token2UUIDdic.ContainsKey(token))
            {
                Logger.Write($"User Login Fail(1:token is used).(token:{token},type:{type})");
                return null;
            }
            string uuid;
            switch (type)
            {
                case "Actor":
                    uuid = global.GenerateUUID();
                    global.Token2UUIDdic.Add(token, uuid);
                    Actor actor = new Actor(uuid);
                    global.UUID2Actor.Add(uuid, actor);
                    Logger.Write($"User Login as Actor.(token:{token},type:{type})");
                    return uuid;
                case "Viewer":
                    uuid = global.GenerateUUID();
                    global.Token2UUIDdic.Add(token, uuid);
                    Viewer viewer = new Viewer(uuid);
                    global.UUID2Viewer.Add(uuid, viewer);
                    Logger.Write($"User Login as Viewer.(token:{token},type:{type})");
                    return uuid;
                default:
                    Logger.Write($"User Login Fail.(token:{token},type:{type})");
                    return null;
            }
        }

        [Route("Logout")]
        [HttpPost]
        public DefaultResponse Logout([FromQuery] string token)
        {
            if (!global.Token2UUIDdic.ContainsKey(token))
            {
                return new DefaultResponse()
                {
                    Success = true,
                    Message = "This Token is not logged in."
                };
            }
            global.UUID2Actor.Remove(global.Token2UUIDdic[token]);
            global.Token2UUIDdic.Remove(token);
            Logger.Write($"User Logout.(token:{token})");
            return DefaultResponse.SuccessNullMessage;
        }
    }
}